# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv
import random


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告


class Europa_Get():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent()  # 禁用服务器缓存
        self.headers = {
            # "User-Agent": ua.random
            # 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15'
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie': 'GUEST_LANGUAGE_ID=en_GB; COOKIE_SUPPORT=true; cookieBannerStatus=shown; ajs_user_id=null; ajs_group_id=null; secalert=rfbnhibbtq; TS01397bd9=010dad8a7afedfc4d8c29c80dd891f7ef163ebfcebd9f7f9f6d981c2ad567f49785f0f81c6c00b5c7ee5b6bc425240a85424c603aec1594ec0c7aa2be9aca31dc5080e95a3; TS01ece425=010dad8a7a3d5754d44d6f0b078403cabd3e52691c0b3601dc052bc13f738180cd378960893692c22bc905d044d6c66727bf64b056; TSPD_101=085d22110bab28005b858a5e86aba8e3a03af14e4faa1ca260bb2e3734bf18f7394c0715716f7e529a35453fbdec1dfa08a2b0d760051800225075386b8ed14e7b19da08c9a73c23a147d78d917b8462; TS011b5b0f=010dad8a7a6782dbb761cd4f576a14fd4baa1212812c34bac69d77c9491d5970f348768341edc1c9be47ef1b057dfe8e38f2a0bf7a; TSf5911152077=085d22110bab280034efecf3f4895b1d8e489983bc67f27d36485b81b2e7c384352801aec54b1c0f7267eab4c324eb37089eaaa486172000f95a5e6a61608041bd55617dde16b5832c1f7c9ec82c87fb9cd2fbcc098bcd5f; TSb41106e7027=085d22110bab2000f4fc0ba6b49cbce0dd9ae6c7d7f3af1dfbde6e1c58fbfaccb5bb6b27ce0e52f8083b319910113000012f93710d38c59cf54b93960470048925d594a9aa5cf48a49d30333583f0f69dfd58c34a544ee8a29045ef55b2f45fc',
            'DNT': '1',
            'Host': 'euipo.europa.eu',
            'Origin': 'https://euipo.europa.eu',
            'Referer': 'https://euipo.europa.eu/eSearch/',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest'
        }


    def get_contents(self, search):
        postData = {
            'start': '0',
            'rows': '100',
            'searchMode': 'advanced',
            'criterion_1': 'ApplicationNumber',
            'term_1': search, #'Bosch Home and Garden',
            'operator_1': 'AND',
            'condition_1': 'IS',
            'sortField': 'MarkVerbalElementText',
            'sortOrder': 'asc'
        }

        resp = HttpUtils.do_request("GET", "https://euipo.europa.eu/TSPD/?type=22", "", "")
        self.cookies.update(resp.cookies.get_dict())

        url = "https://euipo.europa.eu/copla/ctmsearch/json"
        time.sleep(random.randint(2, 4))
        html = HttpUtils.do_request("POST", url, self.headers, postData)

        data_json = json.loads(html.text)
        if data_json['total'] > 0:
            flag = "是"
        else:
            flag = "否"
        # 保存结果
        with open("./XDY_result.csv", 'a+', encoding="utf-8-sig", newline='') as f:
            csv_writer = csv.writer(f)
            csv_writer.writerow([search, flag])
        print(f"==========={flag}=============")


if __name__ == '__main__':
    europa_get = Europa_Get()
    search_list = []
    line_num = 0
    with open("./XDY.csv", 'r', encoding="utf-8-sig", newline='') as f:
        reader = csv.reader(f)
        for line in reader:
            search_list.append(line[0].strip())

    for s in search_list:
        line_num += 1
        print(f"=====line：{line_num}=====search：{s}=============")
        europa_get.get_contents(s)